<template>
  <div class="planet-chart">
    <canvas :id="`planet-chart5${inPage}`"></canvas>
  </div>
</template>

<script>
import Chart from 'chart.js'
import {paneldetailData} from "@/api/system/board"

export default {
  props: ['keyData', 'inPage', 'componentsId', 'indexBox'], // keyData inPage
  name: "board5",
  components: {},
  data() {
    return {
      labels: [
        'temperature',
        'humidity'
      ],
      colorBody: [
        'rgb(255, 99, 132)',
        'rgb(54, 162, 235)',
      ],
      dataBody: [300, 50],
    }
  },
  watch: {
    keyData() {
      if (this.inPage === 'preview') {
        this.getDataLine()
      }
    },
  },
  methods: {
    initFn(labels, dataLine, backgroundColor) {
      const ctx = document.getElementById(`planet-chart5${this.inPage}`);
      const data = {
        labels: labels,
        datasets: [{
          label: 'statistics',
          data: dataLine,
          backgroundColor: backgroundColor,
          borderWidth: 1
        }]
      };
      const config = {
        type: 'pie',
        data: data,
        options: {
          responsive: true, // 设置图表为响应式，根据屏幕窗口变化而变化
          maintainAspectRatio: false,// 保持图表原有比例
          // scales: {
          //   yAxes: [{
          //     ticks: {
          //       beginAtZero:true
          //     }
          //   }]
          // }
        }
      };
      new Chart(ctx, config);
    },
    getDataLine(option) {
      console.log('======>>>keyData', this.keyData)
      let labels_ = []
      let dataBody_ = []
      let colorBody_ = []
      if (this.keyData) {
        for (let index in this.keyData) {
          let item = this.keyData[index]
          labels_.push(item.name ? item.name : (item.sku ? item.sku : `名称${index + 1}`))
          if (this.inPage === 'preview') {
            dataBody_.push((Math.random() * 100).toFixed(1))
          }
          if (this.inPage === 'dataBoard') {
            dataBody_.push(option[index]?(option[index].data || 0):0)
          }
          colorBody_.push(item.body.lineColor)
        }
      }
      console.log('======>>>keyData', labels_, dataBody_, colorBody_)
      this.initFn(labels_, dataBody_, colorBody_)
    }
  },
  mounted() {
    if (this.inPage === 'dataBoard') {
      paneldetailData({id: this.componentsId}).then(res => {
        console.log('统计的数据', res)
        this.getDataLine(res.data)
      })
    } else if (this.inPage === 'compontents') {
      this.initFn(this.labels, this.dataBody, this.colorBody)
    } else {
      this.getDataLine()
    }
    // compontents preview dataBoard
  }
}
</script>

<style scoped>

#planet-chart5 {
  height: 100%;
}
</style>
